<!-- 开户操作 -->
<template>
    <div>
        <navigation-bar :customTitle="curTitle">
            <div class="searchContent">
                <el-select v-model="optionValue" style="width: 100px" size="mini">
                    <el-option v-for="item in options" :value="item.value" :key="item.value" :label="item.label"></el-option>
                </el-select>
                <el-input
                    v-model="ac_name"
                    placeholder="请输入账户名称"
                    size="mini"
                    style="width: 150px; margin-right: 10px; margin-left: 10px"
                ></el-input>
                <custom-button type="search" style="margin-right: 10px" @searchClick="searchClick"></custom-button>
                <custom-button type="reset" style="margin-right: 10px" @resetClick="resetClick"></custom-button>
                <custom-button type="createUser" style="margin-right: 10px" @createUser="createUser"></custom-button>
                <custom-button type="moreUser" style="margin-right: 10px" @moreUser="moreUser"></custom-button>
                <custom-button type="mergeUser" style="margin-right: 10px" @mergeUser="mergeUser"></custom-button>
                <custom-button type="editUser" style="margin-right: 10px" @editUser="editUser"></custom-button>
                <custom-button type="userRemove" style="margin-right: 10px" @userRemove="userRemove"></custom-button>
                <custom-button type="moneyChangeUser" style="margin-right: 10px" @moneyChangeUser="moneyChangeUser"></custom-button>
                <custom-button type="initUser" style="margin-right: 10px" @initUser="initUser"></custom-button>
                <!-- <custom-button type="userZero" style="margin-right: 10px" @userZero="userZero"></custom-button> -->
                <!-- <custom-button type="print" title="打印"></custom-button> -->
            </div>
        </navigation-bar>

        <div>
            <table-index
                :dataSource="dataSource"
                :tableColumns="tableColumns"
                :btnList="btnList"
                :pageSize="pageSize"
                :pageCount="pageCount"
                :pageNo="pageNo"
                @pageChange="pageChange"
                @editRow="editRow"
                selection
                @handleSelectionChange="handleSelectionChange"
                :height="secondTableHeight"
                @lookBgNum="lookBgNum"
                @handleSizeChange="handleSizeChange"
            ></table-index>
        </div>
        <!-- 开户 -->
        <div v-if="showCreateUser" style="text-align: left">
            <custom-dialog title="开户" size="large" @dialogClose="showCreateUser = false">
                <createUser @close="showCreateUser = false"></createUser>
            </custom-dialog>
        </div>

        <!-- 批量开户 -->
        <div v-if="showMoreCreateUser" style="text-align: left">
            <custom-dialog title="批量开户" size="large" @dialogClose="showMoreCreateUser = false">
                <createMoreUser @close="showMoreCreateUser = false" @success="moreSuccess"></createMoreUser>
            </custom-dialog>
        </div>

        <!-- 合并账户 -->
        <div v-if="showMergeUser" style="text-align: left">
            <custom-dialog title="合并账户" size="small" @dialogClose="showMergeUser = false">
                <mergeUser @close="showMergeUser = false" :selectUserList="selectUserList" @success="moreSuccess"></mergeUser>
            </custom-dialog>
        </div>

        <!-- 编辑账户 -->
        <div v-if="showEditUser" style="text-align: left">
            <custom-dialog title="编辑账户" size="large" @dialogClose="showEditUser = false">
                <editUser @close="showEditUser = false" :userInfo="selectUserList" @success="moreSuccess"></editUser>
            </custom-dialog>
        </div>

        <!-- 账户透支额度调整 -->
        <div v-if="showMoneyChangeUser" style="text-align: left">
            <custom-dialog title="账户透支额度调整" size="small" @dialogClose="showMoneyChangeUser = false">
                <moneyChangeUser @close="showMoneyChangeUser = false" :userInfo="selectUserList" @success="moreSuccess"></moneyChangeUser>
            </custom-dialog>
        </div>

        <!-- 账户初始化 -->
        <div v-if="showInitUser" style="text-align: left">
            <custom-dialog title="账户初始化" size="small" @dialogClose="showInitUser = false">
                <initUser @close="showInitUser = false"></initUser>
            </custom-dialog>
        </div>
    </div>
</template>

<script>
import {userManageForm} from '@/assets/form/managementCenter/systemManage/userManage'
import {resetPwdForm} from '@/assets/form/managementCenter/systemManage/resetPwd'
import customDialog from '@/components/customComponents/customDialog'
import customButton from '@/components/customComponents/customForm/customButton'
import formIndex from '@/components/customComponents/customForm/formIndex'
import tableIndex from '@/components/customComponents/customeTable/iviewTable/singleViewTable'
import navigationBar from '@/components/customComponents/managementCenter/navigationBarCustomTitle'
import {AjaxCommon} from '@/libs/apiCommon'
import {CardId} from '@/libs/cardId'
import {PopupCommon} from '@/libs/popupCommon'
import {Utility} from '@/libs/utility'
import plxhOpr from './components/plxhOpr'
import createMoreUser from './components/user/createMoreUser'
import createUser from './components/user/createUser'
import editUser from './components/user/editUser'
import initUser from './components/user/initUser'
import mergeUser from './components/user/mergeUser'
import moneyChangeUser from './components/user/moneyChangeUser'
export default {
    components: {
        navigationBar,
        customButton,
        tableIndex,
        customDialog,
        formIndex,
        plxhOpr,
        createUser,
        createMoreUser,
        mergeUser,
        editUser,
        moneyChangeUser,
        initUser
    },
    data() {
        return {
            showInitUser: false,
            showMoneyChangeUser: false,
            showEditUser: false,
            showMergeUser: false,
            showCreateUser: false,
            showMoreCreateUser: false,
            dialogResetShow: false,
            optionValue: '',
            options: [
                {
                    value: '',
                    label: '所有账户'
                },
                {
                    value: 0,
                    label: '已初始化'
                },
                {
                    value: 9,
                    label: '未初始化'
                }
            ],
            orgInfo: {},
            secondTableHeight: document.body.clientHeight - 225,
            selectUserList: [],
            ac_name: '',
            status: '',
            curTitle: '开户操作',
            statusList: Utility.getDictList('status'),
            // table 相关参数  begin
            dataSource: [],

            // AC_GUID账户GUID、
            // AC_NAME账户名称
            // AC_TYPE账户类型
            //  IS_PUBLIC是否公共账户(0否1是)、
            // AC_SUM账户余额、
            // OVER_SUM透支金额（如为-1无限透支 、0未启用，其它展示金额）
            // ALARM_SUM 告警金额
            // EQ_COUNT账户下设备数、
            // AC_STATE账户状态（0：正常有效 1：被销户 2：被冻结 3：被合并）
            // AC_DATA_STATE账户数据状态（0：正常 1：销户补算 2：合并账户补算 3：调整账户补算 4：换房重算 5：账户清零 6：账户交换 9：新建账户）
            // bgnum透支记录条数（0无 >0可点击查看）

            tableColumns: [
                {
                    type: 'selection',
                    width: 60,
                    align: 'center'
                },
                {
                    type: 'index',
                    width: 60,
                    align: 'center'
                },
                {
                    key: 'AC_NAME',
                    title: '账户名称'
                },
                {
                    key: 'AC_TYPE',
                    title: '账户类型'
                },
                {
                    key: 'IS_PUBLIC',
                    title: '公共账户',
                    slot: 'IS_PUBLIC'
                },
                {
                    key: 'AC_SUM',
                    title: '账户余额'
                },

                {
                    key: 'OVER_SUM',
                    title: '透支金额'
                },
                {
                    key: 'ALARM_SUM',
                    title: '告警金额'
                },

                {
                    key: 'EQ_COUNT',
                    title: '设备数量'
                },
                {
                    key: 'AC_STATE',
                    title: '账户状态',
                    slot: 'AC_STATE'
                },
                {
                    key: 'bgnum',
                    title: '透支额度变更记录',
                    slot: 'bgnum'
                }
                // {
                //     title: '操作',
                //     slot: 'action',
                //     width: 160,
                //     align: 'center'
                // }
            ],
            btnList: ['edit', 'resetPwd', 'delete'],
            pageSize: 20,
            pageCount: 100,
            pageNo: 1,
            // table 相关参数  end

            // 弹窗是否显示
            dialogShow: false,
            // 弹窗标题 (新增修改不同)
            dialogTitle: '',

            // form的配置信息
            formConfig: null,
            type: 'add',

            formResetConfig: resetPwdForm('')
        }
    },
    created() {
        this.formConfig = userManageForm('add')
    },
    methods: {
        lookBgNum(item) {
            console.log(item)
        },
        async userRemove() {
            const selectUserList = this.selectUserList
            if (selectUserList.length < 1) {
                PopupCommon.notify('info', '请选择要注销的账户')
                return
            }
            const ids = selectUserList.map((t) => t.AC_GUID).toString()
            // 判断这些用户能否销户
            const res = await AjaxCommon(`/api/OpenAccount/GetAcsCloseStatus?ac_guids=${ids}`, 'get', null)
            console.log(res)
            if (res.data.Code == 200 && res.data.Message == 'ok') {
                let self = this
                PopupCommon.confirm('确定要注销这些账户吗？')
                    .then((result) => {
                        if (result) {
                            PopupCommon.notify('info', '功能待实现')
                            //                         BatchCloseAc注销用户（支持勾选多个账户）
                            // 但调用此接口前先调用判断接口GetAcsCloseStatus，查看勾选的账户是否不可注销的
                            // 且注销账户进要选择结算方式，实时结算或按最近采集数据结算。如录前17：30，实时结算可能要等到18：00才行，采集结算可能是按17：00的采集数据金额
                        }
                    })
                    .catch((err) => {
                        console.log(err)
                    })
            }
        },
        moreSuccess() {
            this.showMoneyChangeUser = false
            this.showEditUser = false
            this.showMoreCreateUser = false
            this.showMergeUser = false
            this.pageNo = 1
            this.initPage()
        },
        createUser() {
            this.showCreateUser = true
        },
        moreUser() {
            this.showMoreCreateUser = true
        },
        mergeUser() {
            // 合并账户
            const selectUserList = this.selectUserList
            if (selectUserList.length < 2) {
                PopupCommon.notify('info', '最少选择两个账户进行合并')
                return
            }
            this.showMergeUser = true
        },
        editUser() {
            const selectUserList = this.selectUserList
            if (selectUserList.length != 1) {
                PopupCommon.notify('info', '请选择一个账户进行编辑')
                return
            }
            this.showEditUser = true
        },
        moneyChangeUser() {
            const selectUserList = this.selectUserList
            if (selectUserList.length == 0) {
                PopupCommon.notify('info', '请至少选择一个账户进行调整')
                return
            }
            this.showMoneyChangeUser = true
        },
        initUser() {
            const selectUserList = this.selectUserList
            if (selectUserList.length == 0) {
                PopupCommon.notify('info', '请至少选择一个未初始化的账户')
                return
            }
            const userList = selectUserList.filter((t) => t.AC_TYPE == 9)
            if (userList.length == 0) {
                PopupCommon.notify('info', '请选择未初始化的账户')
                return
            }
            const ids = userList.map((t) => t.AC_GUID).toString()
            let self = this
            PopupCommon.confirm('确认初始化这些账户吗?')
                .then(() => {
                    AjaxCommon(`/api/OpenAccount/SetACInit?ac_guids=${ids}`, 'post', {}).then((res) => {
                        if (res?.data?.Code == 200) {
                            PopupCommon.notify('success', '初始化成功')
                            self.initPage()
                        } else {
                            const msg = res?.data?.Message
                            if (msg) {
                                PopupCommon.notify('error', msg)
                            }
                        }
                    })
                })
                .catch(() => {
                    console.log('已取消清零')
                })
            // AC_TYPE
            // 账户初始SetACInit，只能数据表中AC_DATA_STATE账户数据状态为9的数据可进行初始化操作。如勾选的数据中有不为9的提示报错。前端界面可以查询条件过滤未初始化的数据，但页面调用前最好加判断，涉及用户金额必须严谨。
            // this.showInitUser = true
        },
        userZero() {
            PopupCommon.confirm('确认清零这些账户吗?')
                .then(() => {
                    PopupCommon.message('success', '清零成功')
                })
                .catch(() => {
                    console.log('已取消清零')
                })
        },
        getOrgInfo(item) {
            this.orgInfo = item
            this.curTitle = item.fullName
            this.searchClick()
        },
        getHeight() {
            this.secondTableHeight = document.body.clientHeight - 225
        },
        handleSelectionChange(d) {
            this.selectUserList = d
        },
        resetPwdRow(d) {
            let formConfigItem = this.formResetConfig
            formConfigItem.map((t) => {
                Object.keys(t).map((res) => {
                    if (t.fieldName == 'user_id') {
                        t.filedValue = d['user_guid']
                    } else if (t.fieldName == 'LoginName') {
                        t.filedValue = d['user_id']
                    } else if (t.fieldName == 'RealName') {
                        t.filedValue = d['user_name']
                    }
                })
            })
            this.formResetConfig = formConfigItem
            this.dialogResetShow = true
        },
        formInputChange(e) {
            if (e.filedName == 'idCard') {
                const data = CardId.getInfoByCardId(e.value)
                if (data) {
                    let newData = e.allData
                    newData['birthday'] = data.birthday
                    newData['sex'] = data.sex
                    this.$refs.form.changeFormValue(newData)
                }
            }
        },
        resetSubmit(d) {
            // delete d.LoginName
            // delete d.RealName
            let self = this
            AjaxCommon('/api/User/ResetPass', 'post', d).then((res) => {
                if (res?.data?.Code == 200) {
                    PopupCommon.notify('success', '重置成功')
                    self.initPage()
                    self.dialogResetShow = false
                } else {
                    const msg = res?.data?.Message
                    if (msg) {
                        PopupCommon.notify('error', msg)
                    }
                }
            })
        },
        submit(d) {
            let self = this

            if (d.UserGUID) {
                AjaxCommon('/api/User/EditUser', 'post', d).then((res) => {
                    if (res?.data?.Code == 200) {
                        PopupCommon.notify('success', '编辑成功')
                        self.initPage()
                        self.dialogClose()
                    } else {
                        const msg = res?.data?.Message
                        if (msg) {
                            PopupCommon.notify('error', msg)
                        }
                    }
                })
            } else {
                d.Enable = '1'
                delete d.UserGUID
                // 根据类型调用不同接口
                let url = '/api/User/AddUser'
                AjaxCommon(url, 'post', d).then((res) => {
                    if (res?.data?.Code == 200) {
                        PopupCommon.notify('success', '新增成功')
                        self.initPage()
                        self.dialogClose()
                    } else {
                        const msg = res?.data?.Message
                        if (msg) {
                            PopupCommon.notify('error', msg)
                        }
                    }
                })
            }
        },
        dialogClose() {
            this.dialogShow = false
        },
        searchClick() {
            this.pageNo = 1
            this.initPage()
        },
        resetClick() {
            this.ac_name = ''
            this.searchClick()
        },
        addClick() {
            this.formConfig = userManageForm('add')
            let formConfigItem = this.formConfig
            formConfigItem.map((t) => {
                Object.keys(t).map((res) => {
                    if (res == 'fieldName') {
                        t.filedValue = ''
                    }
                })
            })
            this.formConfig = formConfigItem
            this.type = 'add'
            this.dialogTitle = '新增'
            this.dialogShow = true
        },
        // 分页点击事件
        pageChange(p) {
            this.pageNo = p
            this.initPage()
        },
        // 页码点击事件,p当前页
        handleSizeChange(e) {
            this.pageSize = e
            this.pageNo = 1
            this.initPage()
        },
        async editRow(d) {
            this.formConfig = userManageForm('edit')
            // 先获取组织机构的用户信息
            this.type = 'edit'
            let formConfigItem = this.formConfig
            formConfigItem.map((t) => {
                Object.keys(t).map((res) => {
                    if (t.fieldName == 'UserGUID') {
                        t.filedValue = d['user_guid']
                    } else if (t.fieldName == 'LoginName') {
                        t.filedValue = d['user_id']
                    } else if (t.fieldName == 'RealName') {
                        t.filedValue = d['user_name']
                    } else if (t.fieldName == 'Gender') {
                        t.filedValue = d['user_sex']
                    } else if (t.fieldName == 'Phone') {
                        t.filedValue = d['user_m_tel']
                    } else if (t.fieldName == 'Email') {
                        t.filedValue = d['user_email']
                    } else if (t.fieldName == 'Address') {
                        t.filedValue = d['user_address']
                    }
                })
            })
            this.formConfig = formConfigItem
            this.dialogTitle = '编辑'
            this.dialogShow = true
        },
        // 启用或禁用组织机构 isTrue  true禁用 false 不禁用
        useOrg(isTrue) {
            const selectUserList = this.selectUserList
            if (selectUserList.length < 1) {
                PopupCommon.notify('info', '请选择至少一个机构')
                return
            }
            const id = selectUserList.map((t) => t.id).toString()
            let self = this
            let apiUrl = ''
            let tipMsg = ''
            if (isTrue) {
                apiUrl = `api/OrgSysManage/ChangeOrgsDisable`
                tipMsg = '禁用'
            } else {
                apiUrl = 'api/OrgSysManage/ChangeOrgsEnable'
                tipMsg = '启用'
            }
            AjaxCommon(apiUrl, 'post', {orgids: id}).then((res) => {
                console.log(res, 'res...............')
                if (res?.data?.Code == 200) {
                    PopupCommon.notify('success', tipMsg + '成功')
                    self.initPage()
                } else {
                    const msg = res?.data?.Message
                    if (msg) {
                        PopupCommon.notify('error', msg)
                    }
                }
            })
        },
        // 初始化事件
        initPage() {
            let self = this
            self.dataSource = []
            let params = `/api/OpenAccount/GetPageData?PageSize=${this.pageSize}&PageIndex=${this.pageNo}`
            const ac_name = this.ac_name
            if (ac_name != '') {
                params += `&ac_name=${ac_name}`
            }
            const optionValue = this.optionValue
            if (typeof optionValue != 'string') {
                params += `&actype=${optionValue}`
            }
            AjaxCommon(params, 'get', null).then((res) => {
                if (res?.data?.Code == 200) {
                    const data = res?.data.Message
                    const rows = data?.rows
                    rows?.map((t) => {
                        t.AC_SUM = parseFloat(t.AC_SUM).toFixed(2)
                        // 透支金额，如果为-1，无限透支
                        if (parseInt(t.OVER_SUM) == -1) {
                            t.OVER_SUM = '无限透支'
                        } else {
                            t.OVER_SUM = parseFloat(t.OVER_SUM).toFixed(2)
                        }
                        t.ALARM_SUM = parseFloat(t.ALARM_SUM).toFixed(2)
                        return t
                    })

                    self.dataSource = data?.rows
                    self.pageCount = parseInt(data?.total)
                } else {
                    PopupCommon.notify('error', res?.data?.msg)
                }
            })
        }
    },
    mounted() {
        this.$nextTick(() => {
            this.getHeight()
            this.initPage()
        })

        /*窗口自适应，关键代码*/
        window.onresize = () => {
            this.getHeight()
        }
    }
}
</script>

<style></style>
